package com.bci.pwtz.controller;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.bci.pwtz.common.util.PaginationList;
import com.bci.pwtz.common.util.PwtzUtils;
import com.bci.pwtz.exception.CanNotDeleteException;
import com.bci.pwtz.exception.PwtzDatabaseException;
import com.bci.pwtz.exception.PwtzException;
import com.bci.pwtz.mysql.model.Bdz;
import com.bci.pwtz.mysql.model.CompanyUser;
import com.bci.pwtz.mysql.model.Zyxl;
import com.bci.pwtz.service.BdzService;
import com.bci.pwtz.service.BusinessCommonService;
import com.bci.pwtz.service.ZyxlService;

@Controller
@RequestMapping("/user/zyxl")
public class ZyxlController extends AbstractController
{
@Autowired
private ZyxlService service;
@Autowired
private BdzService bdzService;
@Autowired
private BusinessCommonService businessCommonService;

@RequestMapping(value = "/list", method = RequestMethod.POST)
@ResponseBody
public PaginationList<Zyxl> list(String startsubstationcode, String deviceName, int pageSize, int pageNo) throws PwtzException
{

    PaginationList<Zyxl> list = new PaginationList<Zyxl>();
    try
    {
        Long companyid = getLastCompanyId();
        Bdz obj = bdzService.load(startsubstationcode);
        //String devicename, Long companyid, int portalType, String[] medLineCodes, String startsubstationcode, String beginTime, String endTime, int pageSize, int pageNo
        list = service.list(deviceName, companyid,0,null,startsubstationcode,null,null, pageSize, pageNo);
        if(list != null){
            for(int i=0;i<list.getRecords().size();i++){
                if(obj!=null)
                list.getRecords().get(i).setStartsubstationcode(obj.getDevicename());;
            }
        }
        
    }
    catch (PwtzDatabaseException e)
    {
        e.printStackTrace();
    }
    return list;
}
@RequestMapping(value="/load",method=RequestMethod.POST)
@ResponseBody
public Zyxl load(String deviceId){
    Zyxl obj=null;
    try{
        obj=service.load(deviceId);
    }catch(Exception e){
        e.printStackTrace();
    }
    return obj;
}

@RequestMapping(value = "/edite", method = RequestMethod.POST)
@ResponseBody
public Map<String, String> edite(String data)
{
    Map<String, String> map = new HashMap<String, String>();
    try
    {
        //data=java.net.URLDecoder.decode(data,"UTF-8");
        String [] list=decodeURL(data.split("&"));
        for(int i=0;i<list.length;i++){
            String[] array=list[i].split("=");
            if(array.length==1){
                map.put(array[0], "");
            }else{
                map.put(array[0], array[1]);
            }
        }
        int retCount = businessCommonService.getCountByDeviceName(getLastCompanyId(),(long)AbstractController.中压线路, map.get("devicename"),map.get("deviceid"));
        if(retCount>0){
            map = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR, null, "名称已存在！");
            return map;
        }
        CompanyUser user=(CompanyUser) session.getAttribute("user");
        Zyxl device=new Zyxl();
        device.setDeviceid(map.get("deviceid"));
        device.setDevicename(map.get("devicename"));
        device.setAssetnumber(map.get("assetnumber"));
        device.setAssetsnature(map.get("assetsnature"));
        device.setAssetunit(map.get("assetunit"));
        device.setCompanyid(user.getLastCompanyId());
        device.setCreateid(user.getCompanyUserId());
        device.setDevicenumber(map.get("devicenumber"));
        device.setEquipmentstate(map.get("equipmentstate"));
        device.setImportantdegree(map.get("importantdegree"));
        device.setIsgenerationdimension(map.get("isgenerationdimension"));
        device.setIsruralpowernetwork(map.get("isruralpowernetwork"));
        device.setLastoperatorid(user.getCompanyUserId());
        device.setLocalcity(map.get("localcity"));
        device.setMainlinecode(map.get("mainlinecode"));
        if("主线".equals(map.get("devicetype"))){
            device.setMainlinecode(map.get("deviceid"));
        }
        device.setMaintenanceteam(map.get("maintenanceteam"));
        device.setNote(map.get("note"));
        device.setOperationstate(map.get("operationstate"));
        device.setOperationunit(map.get("operationunit"));
        device.setSyncstatus(0);
        device.setVoltagelevel(map.get("voltagelevel"));
//        device.setCablelength(PwtzUtils.passDouble(map.get("cablelength")));
        device.setCablelinklinemode(map.get("cablelinklinemode"));
        device.setCommissioningdate(PwtzUtils.parseDate(map.get("commissioningdate"),"yyyy-MM-dd"));
        device.setConstructionunit(map.get("constructionunit"));
        device.setDevicetype(map.get("devicetype"));
        device.setDispatchtype(map.get("dispatchtype"));
        device.setDispatchunit(map.get("dispatchunit"));
        device.setEquipmentadded(map.get("equipmentadded"));
        device.setEquipmentowner(map.get("equipmentowner"));
        device.setErectmode(map.get("erectmode"));
//        device.setOverheadlinelength(PwtzUtils.passDouble(map.get("overheadlinelength")));
        device.setOverheadlinklinemode(map.get("overheadlinklinemode"));
        device.setPrelinecode(map.get("prelinecode"));
        device.setProjectname(map.get("projectname"));
        device.setProjectnumber(map.get("projectnumber"));
        device.setRegionalcharacteristics(map.get("regionalcharacteristics"));
        device.setStartdevicetype(map.get("startdevicetype"));
        device.setStartpostion(map.get("startposition"));
        device.setStartsubstationcode(map.get("startsubstationcode"));
        device.setStartswitchnumber(map.get("startswitchnumber"));
        device.setSupervisingunit(map.get("supervisingunit"));
//        device.setTotallinelength(PwtzUtils.passDouble(map.get("totallinelength")));
        device.setLinecoloredflag(map.get("linecoloredflag"));
        if(device.getDevicetype().equals("主线")){
            device.setMainlinecode(device.getDeviceid());
        }
        int ret = service.update(device);
        if (ret > 0)
        {
            setLog(device.getDeviceid(), device.getCompanyid(), AbstractController.中压线路, AbstractController.update, "修改中压线路["+device.getDevicename()+"]成功", getUserId());
            map = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_SUCCESS, ERROR_VALUE_MSG_TYPE_INFO, null, "编辑中压线路成功");
        }
        else
        {
            map = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR, null, "编辑中压线路失败");
        }
    }
    catch (PwtzDatabaseException e)
    {
        map = packageException(e);
    }
    catch (UnsupportedEncodingException e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return map;
}

@RequestMapping(value = "/add", method = RequestMethod.POST)
@ResponseBody
public Map<String, String> add(String data)
{
    Map<String, String> map = new HashMap<String, String>();
    try
    {
        //data=java.net.URLDecoder.decode(data,"UTF-8");
        String [] list=decodeURL(data.split("&"));
        for(int i=0;i<list.length;i++){
            String[] array=list[i].split("=");
            if(array.length==1){
                map.put(array[0], "");
            }else{
                map.put(array[0], array[1]);
            }
        }
        int retCount = businessCommonService.getCountByDeviceName(getLastCompanyId(),(long)AbstractController.中压线路, map.get("devicename"));
        if(retCount>0){
            map = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR, null, "名称已存在！");
            return map;
        }
        CompanyUser user=(CompanyUser) session.getAttribute("user");
       Zyxl device=new Zyxl();
        UUID uuid=UUID.randomUUID();
        device.setDeviceid(uuid.toString());
        device.setDevicename(map.get("devicename"));
        device.setAssetnumber(map.get("assetnumber"));
        device.setAssetsnature(map.get("assetsnature"));
        device.setAssetunit(map.get("assetunit"));
        device.setCompanyid(user.getLastCompanyId());
        device.setCreateid(user.getCompanyUserId());
        device.setDevicenumber(map.get("devicenumber"));
        device.setEquipmentstate(map.get("equipmentstate"));
        device.setImportantdegree(map.get("importantdegree"));
        device.setIsgenerationdimension(map.get("isgenerationdimension"));
        device.setIsruralpowernetwork(map.get("isruralpowernetwork"));
        device.setLastoperatorid(user.getCompanyUserId());
        device.setLocalcity(map.get("localcity"));
        device.setMainlinecode(map.get("mainlinecode"));
        if("主线".equals(map.get("devicetype"))){
            device.setMainlinecode(map.get("deviceid"));
        }
        device.setMaintenanceteam(map.get("maintenanceteam"));
        device.setNote(map.get("note"));
        device.setOperationstate(map.get("operationstate"));
        device.setOperationunit(map.get("operationunit"));
        device.setSyncstatus(0);
        device.setVoltagelevel(map.get("voltagelevel"));
//        device.setCablelength(PwtzUtils.passDouble(map.get("cablelength")));
        device.setCablelinklinemode(map.get("cablelinklinemode"));
        device.setCommissioningdate(PwtzUtils.parseDate(map.get("commissioningdate"),"yyyy-MM-dd"));
        device.setConstructionunit(map.get("constructionunit"));
        device.setDevicetype(map.get("devicetype"));
        if("主线".equals(device.getDevicetype())){
            device.setMainlinecode(uuid.toString());
        }
        device.setDispatchtype(map.get("dispatchtype"));
        device.setDispatchunit(map.get("dispatchunit"));
        device.setEquipmentadded(map.get("equipmentadded"));
        device.setEquipmentowner(map.get("equipmentowner"));
        device.setErectmode(map.get("erectmode"));
//        device.setOverheadlinelength(PwtzUtils.passDouble(map.get("overheadlinelength")));
        device.setOverheadlinklinemode(map.get("overheadlinklinemode"));
        device.setPrelinecode(map.get("prelinecode"));
        device.setProjectname(map.get("projectname"));
        device.setProjectnumber(map.get("projectnumber"));
        device.setRegionalcharacteristics(map.get("regionalcharacteristics"));
        device.setStartdevicetype(map.get("startdevicetype"));
        device.setStartpostion(map.get("startposition"));
        device.setStartsubstationcode(map.get("startsubstationcode"));
        device.setStartswitchnumber(map.get("startswitchnumber"));
        device.setSupervisingunit(map.get("supervisingunit"));
//        device.setTotallinelength(PwtzUtils.passDouble(map.get("totallinelength")));
        device.setLinecoloredflag(map.get("linecoloredflag"));
        device = service.add(device);
        if (device !=null)
        {
            setLog(device.getDeviceid(), device.getCompanyid(), AbstractController.中压线路, AbstractController.add, "添加中压线路["+device.getDevicename()+"]成功", getUserId());
            map = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_SUCCESS, ERROR_VALUE_MSG_TYPE_INFO, null, "添加中压线路成功");
            map.put("deviceid", uuid.toString());
        }
        else
        {
            map = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR, null, "添加中压线路失败");
        }
    }
    catch (PwtzDatabaseException e)
    {
        map = packageException(e);
    }
    catch (UnsupportedEncodingException e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return map;
}

@RequestMapping(value="/delete",method=RequestMethod.POST)
@ResponseBody
public Map<String,String> delete(String deviceid){
    Map<String,String> map=new HashMap<String, String>();
    int result=0;
    try
    {
        Zyxl device=service.load(deviceid);
        if(device!=null)
        result=service.delete(deviceid);
        if (result>0)
        {
            setLog(device.getDeviceid(), device.getCompanyid(), AbstractController.中压线路, AbstractController.delete, "删除中压线路["+device.getDevicename()+"]成功", getUserId());
            map = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_SUCCESS, ERROR_VALUE_MSG_TYPE_INFO, null, "删除中压线路成功");
        }
        else
        {
            map = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR, null, "删除中压线路失败");
        }
    }
    catch (PwtzDatabaseException e)
    {
        map = packageException(e);
    }
    catch (CanNotDeleteException e)
    {
        map = packageException(e);
    }
    return map;
}

@RequestMapping(value="/dlist",method=RequestMethod.POST)
@ResponseBody
public List<Zyxl> dlist(Long companyId,String transformercode){
    List<Zyxl> list=new ArrayList<Zyxl>();
    PaginationList<Zyxl> plist=new PaginationList<Zyxl>();
    try{
        plist=service.list(null, companyId, 1, null, transformercode, null, null, 0, 0);
        if(plist!=null&&plist.getRecords()!=null&&plist.getRecords().size()>0){
            list=plist.getRecords();
        }
    }catch(Exception e){
        e.printStackTrace();
    }
    return list;
}
@RequestMapping(value="/plist",method=RequestMethod.POST)
@ResponseBody
public List<Zyxl> plist(String devicetype, String startsubstationcode, String mainlinecode){
    List<Zyxl> list=new ArrayList<Zyxl>();
    try{
        Long companyid=getLastCompanyId();
        list=service.getLineListByType(devicetype,startsubstationcode, mainlinecode, companyid);
    }catch(Exception e){
        e.printStackTrace();
    }
    return list;
}
}
